package com.example.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.book.common.Result;
import com.example.book.entry.Book;
import com.example.book.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/book")
@RestController
public class BookController {

    @Autowired
    private IBookService bookService;

//    获取书籍全部信息
    @GetMapping("/info")
    public Result getBookInfo(){
//        list: mybatis-plus原生方法，不需要写sql
        List<Book> list = bookService.list();
        return Result.success(list);
    }

//    根据id查询书籍信息
    @GetMapping("/id={id}")
    public Result getBookOne(@PathVariable Integer id){
        //        getById: mybatis-plus原生方法，不需要写sql
        Book byId = bookService.getById(id);
        return Result.success(byId);
    }

    //    分页查询书籍数据
    @GetMapping("/page")
    public Result findPage(@RequestParam(name = "pageNum") Integer pageNum,
                           @RequestParam (name = "pageSize") Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String author){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id"); // 根据id进行排序
//        模糊搜索书籍名称
        if (!"".equals(name)){
            queryWrapper.like("name", name);
        }
        Page<Book> page = bookService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}
